<template>
  <Card title="访问来源" :loading="loading">
    <div ref="chartRef" :style="{ width, height }"></div>
  </Card>
</template>
<script lang="ts" setup>
  import { Ref, ref } from 'vue';
  import { Card } from 'ant-design-vue';
  import { useECharts } from '@/hooks/web/useECharts';
  import { PieItem } from '@/api/dashboard/model/data';
  import { dashboardPVSourceApi } from '@/api/dashboard/dashboard';

  defineProps({
    loading: Boolean,
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '300px',
    },
    // start: {
    //   type: String as PropType<string>,
    //   default: '',
    // },
    // end: {
    //   type: String as PropType<string>,
    //   default: '',
    // },
    // pieData: {
    //   type: Array as PropType<PieItem[]>,
    //   default: () => [] as PropType<PieItem[]>,
    // },
    // colors: {
    //   type: Array as PropType<string[]>,
    //   default: () => ['#5ab1ef', '#b6a2de'],
    // },
  });

  const chartRef = ref<HTMLDivElement | null>(null);
  const pieData = ref([] as PieItem[]);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  function drawPie() {
    setOptions({
      tooltip: {
        trigger: 'item',
      },
      legend: {
        bottom: '1%',
        left: 'center',
      },

      series: [
        {
          color: ['#5ab1ef', '#b6a2de'],
          name: '访问来源',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: pieData.value,
          animationType: 'scale',
          animationEasing: 'exponentialInOut',
          animationDelay: function () {
            return Math.random() * 100;
          },
        },
      ],
    });
  }

  function statPvSource(start, end) {
    dashboardPVSourceApi(start, end).then((data: PieItem[]) => {
      if (data && data.length > 0) {
        pieData.value = data;
        drawPie();
      } else {
        pieData.value = [];
        drawPie();
      }
    });
  }
  defineExpose({
    statPvSource,
  });

  // onMounted(() => {
  //   statPvSource();
  // });

  // watch(
  //   () => props.loading,
  //   () => {
  //     if (props.loading) {
  //       return;
  //     }
  //     statPvSource();
  //   },
  //   { immediate: true },
  // );
  // watch(props.pieData, (newValue, oldValue) => {
  //   console.log(`Message changed from ${oldValue} to ${newValue}`);
  // });
</script>
